package LeetCode2018;

/**
 * Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
   Output: 7 -> 0 -> 8
   Explanation: 342 + 465 = 807.
 * @leiwenkang 2018-03-30 11:41.
 */
public class LeetCode002 {
    public static void main(String[] args) {
          ListNode l1 = new ListNode(9);
//          ListNode p2 = new ListNode(4);
//          ListNode p3 = new ListNode(3);
//          l1.next = p2;
//          p2.next = p3;
          l1.next = null;

        ListNode l2 = new ListNode(9);
//        ListNode v2 = new ListNode(6);
//        ListNode v3 = new ListNode(4);
//
//        l2.next = v2;
//        v2.next = v3;
        l2.next = null;

        ListNode result = addTwoNumbers(l1, l2);
        while (result != null) {
            System.out.println(result.val);
            result = result.next;
        }

    }
    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode p1 = l1;
        ListNode p2 = l2;
        ListNode result = null;
        ListNode p3 = null;
        int takeOVer = 0;//表示进位
        while (p1 != null || p2 != null) {
            int add1 = 0;
            if (p1 != null) {
                add1 = p1.val;
                p1 = p1.next;
            }
            int add2 = 0;
            if (p2 != null) {
                add2 = p2.val;
                p2 = p2.next;
            }
            int sum = add1 + add2 + takeOVer;
            if (sum >= 10) {
                sum -= 10;
                takeOVer = 1;
            } else {
                takeOVer = 0;
            }
            ListNode temp = new ListNode(sum);
            if (result == null) {
                result = temp;
            } else {
                p3.next = temp;
            }
            p3 = temp;
        }
        if (takeOVer == 1) {
            ListNode temp = new ListNode(1);
            p3.next = temp;
            temp.next = null;
        } else {
            p3.next = null;
        }
        return result;
    }
}
